package cn.mrcode.fd.blog.services.impl;

import cn.mrcode.fd.blog.common.BusConstant;
import cn.mrcode.fd.blog.common.UserDefaultEnum;
import cn.mrcode.fd.blog.dao.mapper.BlogConfigMapper;
import cn.mrcode.fd.blog.dao.mapper.LoginInfoMapper;
import cn.mrcode.fd.blog.dao.mapper.UserMapper;
import cn.mrcode.fd.blog.dao.mappercu.LoginInfoCuMapper;
import cn.mrcode.fd.blog.dto.ConQQDto;
import cn.mrcode.fd.blog.dto.RegistDto;
import cn.mrcode.fd.blog.dto.account.RegisterResData;
import cn.mrcode.fd.blog.entity.BlogConfig;
import cn.mrcode.fd.blog.entity.LoginInfo;
import cn.mrcode.fd.blog.entity.User;
import cn.mrcode.fd.blog.entityCu.BlogConfigCu;
import cn.mrcode.fd.blog.entityCu.UserCu;
import cn.mrcode.fd.blog.enu.AccountError;
import cn.mrcode.fd.blog.services.IAccountService;
import cn.mrcode.fd.blog.services.IBlogConfigService;
import cn.mrcode.fd.blog.services.IUserService;
import cn.mrcode.fd.plugin.security.exception.AuthcException;
import cn.mrcode.fd.plugin.security.helper.SecurityHelper;
import cn.mrcode.fd.utils.UUID;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 账户服务实现
 *
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2015/12/25 21:14
 */
@Service
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private LoginInfoMapper loginInfoMapper;
    @Autowired
    private LoginInfoCuMapper loginInfoCuMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BlogConfigMapper blogConfigMapper;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IBlogConfigService iBlogConfigService;

    @Override
    public LoginInfo findByAccount(String account) {
        LoginInfo record = new LoginInfo();
        record.setAccount(account);
        List<LoginInfo> loginInfos = loginInfoCuMapper.selectSelective(record);
        if(CollectionUtils.isEmpty(loginInfos)){
            return null;
        }
        return loginInfos.get(0);
    }

    @Override
    public LoginInfo findByEmail(String email) {
        LoginInfo record = new LoginInfo();
        record.setEmail(email);
        List<LoginInfo> loginInfos = loginInfoCuMapper.selectSelective(record);
        if(CollectionUtils.isEmpty(loginInfos)){
            return null;
        }
        return loginInfos.get(0);
    }

    @Override
    @Transactional
    public RegisterResData register(RegistDto registDto) {
        String account = registDto.getAccount();
        String email = registDto.getEmail();
        String password = registDto.getPassword();
        boolean isCanUsed_account =  isCanUsed_account(account);
        if(!isCanUsed_account){
           return new RegisterResData(false, AccountError.ACCOUNT_NOT_CANUSE);
        }
        LoginInfo _eloginInfo = findByEmail(email);
        if(_eloginInfo != null){
            return new RegisterResData(false, AccountError.EMAIL_NOT_CANUSE);
        }

        User user = new User();
        user.setCreateTime(new Date());
        user.setCreateBy(BusConstant.Sysuser.SYS_USER_ID);
        user.setAccount(account);
        user.setEmail(email);
        user.setId(UUID.uuid());
        user.setPassword(DigestUtils.md5Hex(password));
        user.setHeadImg(UserDefaultEnum.HEAD_IMG.getValue());
        user.setName(account); //默认用户名称昵称等于账户
        user.setSign(UserDefaultEnum.SIGN.getValue());
        userMapper.insertSelective(user);

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setPassword(user.getPassword());
        loginInfo.setId(UUID.uuid());
        loginInfo.setEmail(user.getEmail());
        loginInfo.setAccount(user.getAccount());
        loginInfo.setCreateBy(user.getCreateBy());
        loginInfo.setCreateTime(user.getCreateTime());
        loginInfo.setPassword(user.getPassword());
        loginInfo.setUserId(user.getId());
        loginInfoMapper.insertSelective(loginInfo);

        BlogConfig blogConfig = new BlogConfig();
        blogConfig.setId(UUID.uuid());
        blogConfig.setUserId(user.getId());
        blogConfig.setCreateBy(BusConstant.Sysuser.SYS_USER_ID);
        blogConfig.setCreateTime(new Date());
        blogConfig.setHanderBg(BusConstant.DefaultConfig.USER_HANDER_BG);
        blogConfig.setBlogShow(BusConstant.DefaultConfig.BLOG_SHOW);
        blogConfigMapper.insertSelective(blogConfig);
        return new RegisterResData(true);
    }

    @Override
    @Transactional
    public String insertCon_QQ_1(ConQQDto conQQDto, String sysUserId) {
        String account = conQQDto.getAccount();
        String nickname = conQQDto.getNickname();
        String figureurl_2 = conQQDto.getFigureurl_2();
        String openid = conQQDto.getOpenid();

        User user = new User();
        user.setCreateTime(new Date());
        user.setCreateBy(sysUserId);
        user.setAccount(account);
        user.setId(UUID.uuid());
        user.setSign("这位童鞋很懒，什么也没有留下～～！");

        if(StringUtils.isBlank(nickname)){
            nickname = account;
        }
        if(StringUtils.isBlank(figureurl_2)){
            figureurl_2 = BusConstant.DefaultConfig.HEAD_IMG;
        }

        user.setHeadImg(figureurl_2);
        user.setName(nickname);
        String noMd5Password = "123456";
        user.setPassword(DigestUtils.md5Hex(noMd5Password));
        userMapper.insertSelective(user);

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setPassword(user.getPassword());
        loginInfo.setId(UUID.uuid());
        loginInfo.setEmail(user.getEmail());
        loginInfo.setAccount(user.getAccount());
        loginInfo.setCreateBy(user.getCreateBy());
        loginInfo.setCreateTime(user.getCreateTime());
        loginInfo.setPassword(user.getPassword());
        loginInfo.setUserId(user.getId());
        loginInfo.setQqQzOpenid(openid);  //qq互联唯一标识
        loginInfoMapper.insertSelective(loginInfo);

        BlogConfig blogConfig = new BlogConfig();
        blogConfig.setId(UUID.uuid());
        blogConfig.setUserId(user.getId());
        blogConfig.setCreateBy(BusConstant.Sysuser.SYS_USER_ID);
        blogConfig.setCreateTime(new Date());
        blogConfig.setHanderBg(BusConstant.DefaultConfig.USER_HANDER_BG);
        blogConfig.setBlogShow(BusConstant.DefaultConfig.BLOG_SHOW);
        blogConfigMapper.insertSelective(blogConfig);

        return noMd5Password;
    }

    @Override
    public Set<String> findRoleNameSet(String account) {
        return new HashSet<String>();
    }

    @Override
    public Set<String> findPermissionNameSet(String roleName) {
        return new HashSet<String>();
    }

    @Override
    public boolean isCanUsed_account(String account) {
        LoginInfo _loginInfo = findByAccount(account);
        if (_loginInfo != null) {
            return false;
        } else {
            if (BusConstant.DisableAccount.isDisable(account)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public UserCu qq_login(String openid) {
        LoginInfo record = new LoginInfo();
        record.setQqQzOpenid(openid);
        List<LoginInfo> loginInfos = loginInfoCuMapper.selectSelective(record);
        if(CollectionUtils.isEmpty(loginInfos)){
            return null;
        }

        LoginInfo loginInfo = loginInfos.get(0);
        try {
            SecurityHelper.login(loginInfo.getAccount(), loginInfo.getPassword());
            UserCu user = iUserService.findUserCu(loginInfo.getAccount());
            BlogConfigCu blogConfigCu = iBlogConfigService.findBlogConfigCu(user.getId());
            user.setBlogConfig(blogConfigCu);
            return user;
        } catch (AuthcException e) {
            e.printStackTrace();
            return null;
        } catch (Exception e) {
           throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional
    public String updateCon_QQ_2(ConQQDto conQQDto, String sysUserId) {
        String openid = conQQDto.getOpenid();
        LoginInfo record = new LoginInfo();
        record.setQqQzOpenid(openid);
        List<LoginInfo> loginInfos = loginInfoCuMapper.selectSelective(record);
        if(CollectionUtils.isNotEmpty(loginInfos)){ //不为空，标识已经被绑定了
            return "该QQ号可能已经被账户:" + loginInfos.get(0).getAccount() + "绑定使用，如果此账户不是您的，请联系我们";
        }
        record = new LoginInfo();
        record.setAccount(conQQDto.getAccount());
        List<LoginInfo> lis = loginInfoCuMapper.selectSelective(record);
        if(CollectionUtils.isNotEmpty(lis) && lis.size() == 1){
            LoginInfo db_li = lis.get(0);
            db_li.setQqQzOpenid(openid);
            db_li.setModBy(sysUserId);
            db_li.setModTime(new Date());
            loginInfoMapper.updateByPrimaryKey(db_li);
        }

        return null;
    }


}
